package com.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.common.utils.StringUtils;
import com.domain.entity.DiyTable;
import com.mapper.DiyTableMapper;
import com.service.IDiyTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;


@Service
public class DiyTableServiceImpl implements IDiyTableService {
    @Autowired
    private DiyTableMapper diyTableMapper;


    @Override
    public List<Map<String,String>> getColData(Map<String,String> map) {
        String nameLocal = map.get("nameLocal");
        String tableName = map.get("tableName");
        String name = map.get("name");
        if (StringUtils.isEmpty(nameLocal) || StringUtils.isEmpty(tableName))return  null;
        switch (name){
         
        }
        return null;
    }

    @Override
    public JSONObject getList(List<DiyTable> diyTables) {
        if (StringUtils.isEmpty(diyTables)) return null;
        List<DiyTable> allLists = new ArrayList<>();
        for (DiyTable diyTable: diyTables){
            List<DiyTable> list = diyTableMapper.getList(diyTable);
            allLists.addAll(list);
        }

        return buildResult(allLists);
    }


    public static JSONObject buildResult(List<DiyTable> allLists) {
        // 按topRowKey 聚合
        Map<String, List<DiyTable>> groupedByTopRowKey = allLists.stream()
                .collect(Collectors.groupingBy(DiyTable::getTopRowKey));

        JSONArray innerArray = new JSONArray();

        for (Map.Entry<String, List<DiyTable>> entry : groupedByTopRowKey.entrySet()) {
            String topRowKey = entry.getKey();
            List<DiyTable> items = entry.getValue();

            JSONArray valueArray = new JSONArray();
            for (DiyTable item : items) {
                JSONObject valueItem = new JSONObject();
                valueItem.put("rowKey", item.getRowKey());
                valueItem.put("colKey", item.getColKey());
                valueItem.put("count", item.getCount());
                valueArray.add(valueItem);
            }

            JSONObject topItem = new JSONObject();
            topItem.put("topRowKey", topRowKey);
            topItem.put("value", valueArray);

            innerArray.add(topItem);
        }

        JSONArray resultArray = new JSONArray();
        resultArray.add(innerArray);

        JSONObject finalResult = new JSONObject();
        finalResult.put("result", resultArray);

        return finalResult;
    }

}
